package com.gorkr.hot100.medium;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

import org.junit.Test;

import com.gorkr.common.ListNode;

/**
 * @author 张心宇 <zhangxinyu20@kuaishou.com>
 * Created on 2022-12-26
 */
public class M148SortList {

    public ListNode sortList(ListNode head) {

        if (head == null) {
            return null;
        }

        return sort(head);
    }

    private ListNode sort(ListNode head) {
        ListNode low = head, fast = head.next;
        if (fast == null) {
            return low;
        }

        while (fast != null && fast.next != null) {
            low = low.next;
            fast = fast.next.next;
        }
        ListNode secondHead = low.next;
        low.next = null;
        // merge
        return merge(sort(head), sort(secondHead));
    }

    /**
     * 2 -> 3
     * 1->4->6
     */
    private ListNode merge(ListNode low, ListNode secondHead) {
        ListNode p = low, q = secondHead;
        ListNode head = new ListNode(-1);
        ListNode now = head;
        while (p != null && q != null) {
            if (p.val < q.val) {
                now.next = p;
                p = p.next;
            } else {
                now.next = q;
                q = q.next;
            }
            now = now.next;
        }
        if (q != null) {
            now.next = q;
        } else {
            now.next = p;
        }
        return head.next;
    }

    @Test
    public void test() {
        ListNode head = new ListNode(4);
        head.next = new ListNode(2);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(3);
        sortList(head);
    }
}
